package com.zn.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zn.common.constants.Constants;
import com.zn.common.resp.ApiResult;
import com.zn.common.utils.FileUtils;
import com.zn.dto.UserDTO3;
import com.zn.pojo.*;
import com.zn.pojo.android.*;
import com.zn.pojo.android.dto.VehicleBeanDTO;
import com.zn.services.MhyService;
import com.zn.services.UserService;
import com.zn.services.VehicleService;
import com.zn.services.VeiReportInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;


@Controller
@RequestMapping("vehicle")
public class VehicleController {

    @Autowired
    private MhyService mhyService;
    @Autowired
    private VehicleService vehicleService;
    @Autowired
    private VeiReportInfoService veiReportInfoService;
    @Autowired
    private UserService userService;


    @GetMapping("/getByProcessNo")
    @ResponseBody
    public ApiResult<Integer> getProcessDataByProcessNo(@RequestParam String processNo) {
        if (StringUtils.isEmpty(processNo)) {
            return new ApiResult<>(500, "流水号不能为空!");
        }
        VehicleBean vb = vehicleService.getByProcessNo(processNo);
        if (ObjectUtils.isEmpty(vb)) {
            return new ApiResult<>(500, "未找到此流水号:" + processNo + ",下的数据!");
        }
        return new ApiResult<>(vb.getVehicleId());
    }
    @GetMapping("/getByMhyPlate")
    @ResponseBody
    public ApiResult<Integer> getProcessDataByMhyPlate(@RequestParam String mhyPlate) {
        if (StringUtils.isEmpty(mhyPlate)) {
            return new ApiResult<>(500, "车牌号不能为空!");
        }
        VehicleBean vb = vehicleService.getByMhyPlate(mhyPlate);
        if (ObjectUtils.isEmpty(vb)) {
            return new ApiResult<>(500, "未找到此车牌号:" + mhyPlate + ",下的数据!");
        }
        return new ApiResult<>(vb.getVehicleId());
    }


    @GetMapping("/view")
    public ModelAndView view(@RequestParam Integer vId) {
        ModelAndView mav = new ModelAndView("admin_view/vehicle_info");
        UnifiedReportData data = vehicleService.assembleData(vId);
        List<ProcessData> pds = data.getProcessData();
        List<String> s1 = new ArrayList<>();
        List<String> s2 = new ArrayList<>();
        List<String> s3 = new ArrayList<>();
        List<String> z1 = new ArrayList<>();
        List<String> z2 = new ArrayList<>();
        List<String> z3 = new ArrayList<>();
        List<String> rpms = new ArrayList<>();
        List<Integer> idxs = new ArrayList<>();
        int count = 1;
        if (!ObjectUtils.isEmpty(pds)) {
            for (ProcessData pd : pds) {
                switch (pd.getTestIdx()) {
                    case 1:
                        if (s3.size() != 0 || s2.size() != 0) {
                            s1 = new ArrayList<>();
                            s2 = new ArrayList<>();
                            s3 = new ArrayList<>();
                            z1 = new ArrayList<>();
                            z2 = new ArrayList<>();
                            z3 = new ArrayList<>();
                            count = 1;
                        }
                        s1.add(pd.getSmoke());
                        z1.add(pd.getRpm());
                        break;
                    case 2:
                        s2.add(pd.getSmoke());
                        z2.add(pd.getRpm());
                        break;
                    case 3:
                        s3.add(pd.getSmoke());
                        z3.add(pd.getRpm());
                        break;
                    default:
                        break;
                }
                idxs.add(count++);
                rpms.add(pd.getRpm());
            }
        }
        mav.addObject("s1", s1);
        mav.addObject("s2", s2);
        mav.addObject("s3", s3);
        mav.addObject("z1", z1);
        mav.addObject("z2", z2);
        mav.addObject("z3", z3);
        mav.addObject("idxs", idxs.subList(0, Math.min(Math.min(s1.size(), s2.size()), s3.size())));
        mav.addObject("data", data);
        return mav;
    }


    /**
     * 上传 基本信息实体类
     *
     * @param baseMsgUpload
     * @return
     */
    @PostMapping("add")
    @ResponseBody
    public ApiResult add(@RequestBody BaseMsgUpload baseMsgUpload) {
        int count = vehicleService.add(baseMsgUpload);
        //todo 生成报告
        VeiReportInfo info = new VeiReportInfo();
        VehicleBean vehicle = baseMsgUpload.getVehicle();
        info.setAgentName(vehicle.getOwnerName());
        info.setAgentPhone(vehicle.getOwnerMobile());
        info.setAgentAddress(vehicle.getOwnerAddress());
        info.setEquipmentManufacturer(vehicle.getMhyManu());
        info.setEngineManufacturerName(vehicle.getNgManu());
        info.setMachineNumber(vehicle.getMhyModel());
        info.setProductionDate(vehicle.getNgProdDate());
        info.setEquipmentColor(vehicle.getMhyColor());
        info.setEquipmentNumber(vehicle.getMhyFrameNo());
        info.setTrademark(vehicle.getMhyBrand());
        info.setEngineNumber(vehicle.getNgNo());
        info.setEmissionPeriod(vehicle.getEmissionLevel());
        info.setEngineModel(vehicle.getNgModel());
        info.setEngineYear(vehicle.getNgProdDate());
        info.setEnginePower(vehicle.getNgPower());
        info.setProtectionNumber(vehicle.getNgEcoOpenNo());
        info.setMachineType(vehicle.getMhyType());
        info.setWorkCharacteristic(vehicle.getNgOpPerfm());
        info.setEngineAftertreatmentSystem(vehicle.getNgPostTreatment());
        info.setUuid(vehicle.getUuid());
        VeiReportInfo reportByUUId = veiReportInfoService.getReportByUUId(vehicle.getUuid());
        if (ObjectUtils.isEmpty(reportByUUId)) {
            veiReportInfoService.addVeiReportInfo(0, info, 53);
        } else {
            info.setReportId(reportByUUId.getReportId());
            veiReportInfoService.modifyReportByRid(info);
        }
        return new ApiResult();
    }

    /**
     * 上传检测过程照片
     *
     * @param vi
     * @return
     */
    @PostMapping("/image/upload")
    @ResponseBody
    public ApiResult imageUpload(@RequestBody @Validated VehicleImage vi) {
        int count = 0;
        MhyMedia media = mhyService.getMhyMediaByUUId(vi.getUuid());
        vi.setFileData(FileUtils.Base64ToImage(vi.getFileData()));
        if (ObjectUtils.isEmpty(media)) {
            count = mhyService.addMhyMedia(vi);
        } else {
            count = mhyService.modifyMhyMedia(vi, media.getMediaId());
        }
        if (count == 0) {
            return new ApiResult(500, "上传错误, 请对照字段");
        }
        //todo 生成报告
        if (!StringUtils.isEmpty(vi.getUuid())) {
            VeiReportInfo info = veiReportInfoService.getReportByUUId(vi.getUuid());
            if (!ObjectUtils.isEmpty(info)) {
                int count2 = veiReportInfoService.modifyAndroidReportImage(info, vi);
            }
        }
        return new ApiResult();
    }

    @PostMapping("/upload/report2/baseDetectionInfo")
    @ResponseBody
    public ApiResult report2ImageUpload(@RequestBody VeiReportInfo2 info) {
        if (StringUtils.isEmpty(info.getUuid())) {
            return new ApiResult(500, "uuid不能为null");
        }
        info.setProjectName("委托检测");
        info.setCheckCategory("非道路柴油移动机械排气检测");
        VeiReportInfo2 report = veiReportInfoService.getReport2ByUUId(info.getUuid());
        if (!ObjectUtils.isEmpty(report)) {
            info.setReport2Id(report.getReport2Id());
            veiReportInfoService.modifyReportInfo2(info);
            return new ApiResult(200, "重复提交已覆盖!");
        }
        info.setCreateTime(new Date());
        //todo 根据上传的编号 进行分配
        int userId = assignReport(info.getReportNumber());
        int count = veiReportInfoService.addVeiReport2Info(info, userId, 0);
        if (count == 1) {
            return new ApiResult();
        } else {
            return new ApiResult(500, "上传失败!");
        }
    }

    @PostMapping("/upload/report2/image")
    @ResponseBody
    public ApiResult report2BaseInfoUpload(@RequestBody @Validated VehicleImage vi) {
        if (StringUtils.isEmpty(vi.getUuid())) {
            return new ApiResult(500, "uuid不能为null");
        }
        VeiReportInfo2 report = veiReportInfoService.getReport2ByUUId(vi.getUuid());
        if (ObjectUtils.isEmpty(report)) {
            return new ApiResult(500, "无法对应到此uuid:" + vi.getUuid());
        }
        vi.setFileData(FileUtils.Base64ToImage(vi.getFileData()));
        int count = veiReportInfoService.modifyReport2Image(report, vi);
        if (count == 1) {
            return new ApiResult();
        } else {
            return new ApiResult(500, "上传失败!");
        }
    }

    @PostMapping("/upload/report/baseDetectionInfo")
    @ResponseBody
    public ApiResult reportInfoUpload(@RequestBody VeiReportInfo info) {
        if (StringUtils.isEmpty(info.getUuid())) {
            return new ApiResult(500, "uuid不能为null");
        }
        VeiReportInfo report = veiReportInfoService.getReportByUUId(info.getUuid());
        if (!ObjectUtils.isEmpty(report)) {
            info.setReportId(report.getReportId());
            veiReportInfoService.modifyReportByRid(info);
            return new ApiResult(200, "重复提交已覆盖!");
        }
        info.setCreateTime(new Date());
        //todo 根据上传的编号 进行分配
        int userId = assignReport(info.getReportNumber());
        int count = veiReportInfoService.addVeiReportInfo(0, info, userId);
        if (count == 1) {
            return new ApiResult();
        } else {
            return new ApiResult(500, "上传失败!");
        }
    }

    private int assignReport(String reportNumber) {
        if (StringUtils.isEmpty(reportNumber) || reportNumber.length() < 6) {
            return 54;
        }
        List<UserDTO3> users = userService.getByRoleId(Constants.ROLE_ORDINARY_USER);
        users.stream().filter(us -> us.getUsername() != null && us.getUsername().length() == 6);
        for (UserDTO3 user : users) {
            if (user.getUsername().toLowerCase().equals(reportNumber.substring(0, 6).toLowerCase())) {
                return user.getUserId();
            }
        }
        return 54;
    }

    @PostMapping("/upload/report/image")
    @ResponseBody
    public ApiResult reportImageUpload(@RequestBody @Validated VehicleImage vi) {
        if (StringUtils.isEmpty(vi.getUuid())) {
            return new ApiResult(500, "uuid不能为null");
        }
        VeiReportInfo report = veiReportInfoService.getReportByUUId(vi.getUuid());
        if (ObjectUtils.isEmpty(report)) {
            return new ApiResult(500, "无法对应到此uuid:" + vi.getUuid());
        }
        vi.setFileData(FileUtils.Base64ToImage(vi.getFileData()));
        int count = veiReportInfoService.modifyReportImage(report, vi);
        if (count == 1) {
            return new ApiResult();
        } else {
            return new ApiResult(500, "上传失败!");
        }
    }

    @GetMapping("/view-all")
    @ResponseBody
    public PageQueryBean getAllVehicle(PageQueryBean pqb) {
        PageHelper.startPage(pqb.getStartRow(), pqb.getPageSize());
        List<VehicleBeanDTO> all = vehicleService.getAll();
        PageInfo<VehicleBeanDTO> info = new PageInfo<>(all);
        pqb.setTotalRows(new Long(info.getTotal()).intValue());
        pqb.setItems(all);
        return pqb;
    }

    /**
     * 腾源账号查看 个人数据信息 processNo.com_no = 063
     * @param
     * @return
     */
    @GetMapping("/view/by")
    @ResponseBody
    public List<VehicleBeanDTO> getAllVehicleTy(@RequestParam String comOn) {
        return vehicleService.getByProcessNoComOn(comOn);
    }


    @GetMapping("/view_all")
    public ModelAndView vehicleViewAll(HttpServletRequest request) {
        Integer role = (Integer) request.getSession().getAttribute(request.getSession().getId());
        ModelAndView mav = new ModelAndView("admin_view/vehicle_table");
        mav.addObject("role", role);
        return mav;
    }

    @GetMapping("/get")
    @ResponseBody
    public ApiResult getMhyPlate(@RequestParam String mhyPlate){
        if (StringUtils.isEmpty(mhyPlate)) {
            return new ApiResult(500,"车牌号不能为空！");
        }
        VehicleBean vb = vehicleService.getByMhyPlate(mhyPlate);
        if(ObjectUtils.isEmpty(vb)){
            return new ApiResult(500,"未查询到此"+mhyPlate+"车牌号下的uuid");
        }
        return new ApiResult(vb.getUuid());
    }


    private String mapEmissionPeriod(String str) {
        String temp = "";
        switch (str) {
            case "国一":
                temp = "I";
                break;
            case "国二":
                temp = "II";
                break;
            case "国三":
                temp = "III";
                break;
            default:
                break;
        }
        return temp;
    }

    private Integer mapVisualPlume(String str) {
        Integer temp = null;
        switch (str) {
            case "不可见":
                temp = 0;
                break;
            case "可见":
                temp = 1;
                break;
            default:
                break;
        }
        return temp;
    }
}
